package com.cdream.basic.util;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;

public class ProtoStuffUtil {
    /**
     * 将指定对象序列化为byte数组
     * @param source
     * @param <T>
     * @return
     */
    public static <T> byte[] serialize(T source) {
        LinkedBuffer buffer = null;
        try {
            RuntimeSchema<T> schema = RuntimeSchema.createFrom((Class<T>) source.getClass());
            buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
            return ProtostuffIOUtil.toByteArray(source, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("ProtostuffUtils serialize exception");
        } finally {
            if (buffer != null) {
                buffer.clear();
            }
        }
    }

    /**
     * 将byte数组反序列化为指定对象
     * @param source
     * @param typeClass
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] source, Class<T> typeClass) {
        try {
            RuntimeSchema<T> schema = RuntimeSchema.createFrom(typeClass);
            T newInstance = typeClass.newInstance();
            ProtostuffIOUtil.mergeFrom(source, newInstance, schema);
            return newInstance;
        } catch (Exception e) {
            throw new RuntimeException("ProtostuffUtils deserialize exception");
        }
    }
}
